package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.OutboundDetailQueryDTO;
import com.intelligent.dto.OutboundOrderQueryDTO;
import com.intelligent.pojo.*;
import com.intelligent.service.*;
import com.intelligent.mapper.OutboundDetailMapper;
import com.intelligent.vo.OutboundDetailVO;
import com.intelligent.vo.OutboundOrderVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author 86188
* @description 针对表【outbound_detail(出库明细信息表)】的数据库操作Service实现
* @createDate 2025-08-29 11:59:52
*/
@Service
public class OutboundDetailServiceImpl extends ServiceImpl<OutboundDetailMapper, OutboundDetail>
    implements OutboundDetailService{
    @Autowired
    private TUserService userService;

    @Autowired
    private SalesOrdersService salesOrdersService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private ProductionWorkOrdersService productionWorkOrdersService;
    @Autowired
    private OutboundService outboundService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UnitService unitService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private OutboundDetailService outboundDetailService;

    @Override
    public IPage<OutboundOrderVO> pageList(OutboundOrderQueryDTO query) {
        // 1. 设置分页参数
        Page<OutboundDetail> page = new Page<>(
                query.getPageNum() != null ? query.getPageNum() : 1,
                query.getPageSize() != null ? query.getPageSize() : 5
        );

        // 2. 构建查询条件
        LambdaQueryWrapper<OutboundDetail> wrapper = new LambdaQueryWrapper<>();

        // 关键词模糊查询（支持出库单号、备注）
        if (StringUtils.isNotBlank(query.getKeyword())) {
            wrapper.and(w -> w.like(OutboundDetail::getOutboundNo, query.getKeyword())
                    .or().like(OutboundDetail::getRemark, query.getKeyword()));
        }

        // 出库单号模糊查询（如果单独提供）
        if (StringUtils.isNotBlank(query.getOutboundNo())) {
            wrapper.like(OutboundDetail::getOutboundNo, query.getOutboundNo());
        }

        // 出库类型查询
        if (query.getOutboundType() != null) {
            wrapper.eq(OutboundDetail::getOutboundType, query.getOutboundType());
        }

        // 出库状态查询
        if (query.getOutboundStatus() != null) {
            wrapper.eq(OutboundDetail::getOutboundStatus, query.getOutboundStatus());
        }


        // 3. 执行分页查询
        IPage<OutboundDetail> outboundPage = this.page(page, wrapper);

        // 4. 转换为VO对象
        return outboundPage.convert(outboundDetail -> {
            OutboundOrderVO vo = new OutboundOrderVO();
            BeanUtils.copyProperties(outboundDetail, vo);

            // 设置用户信息
            if (outboundDetail.getUId() != null) {
                TUser user = userService.getById(outboundDetail.getUId());
                if (user != null) {
//                    vo.setUId(user.getUserId());
                    vo.setUsername(user.getUsername());
                }
            }

            if (outboundDetail.getSaleOrdersId() != null) {
                SalesOrders salesOrders = salesOrdersService.getById(outboundDetail.getSaleOrdersId());
                if (salesOrders != null) {
                    vo.setOrderNo(salesOrders.getOrderNo());
                }
            }

            if (outboundDetail.getProductWorkId() != null) {
                ProductionWorkOrders productionWorkOrders = productionWorkOrdersService.getById(outboundDetail.getProductWorkId());
                if (productionWorkOrders != null) {
                    vo.setWorkOrderNo(productionWorkOrders.getWorkOrderNo());
                }
            }

            if (outboundDetail.getPurchaseId() != null) {
                PurchaseOrder purchaseOrder = purchaseOrderService.getById(outboundDetail.getPurchaseId());
                if (purchaseOrder != null) {
                    vo.setPurchaseOrderNo(purchaseOrder.getOrderNo());
                }
            }

            return vo;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(OutboundDetail outboundDetail) {
        // 设置创建时间
//        outboundDetail.setCreateTime(LocalDateTime.now());
        // 设置出库单状态为待出库
        outboundDetail.setOutboundStatus(0);
        // 生成出库单号: CK + 年月日 + 4位随机数
        String outboundNo = "CK" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"))
                + String.format("%04d", (int)(Math.random() * 10000));
        outboundDetail.setOutboundNo(outboundNo);

        // 2. 设置出库时间
        if (outboundDetail.getOutboundTime() == null) {
            outboundDetail.setOutboundTime(new java.util.Date());
        }

        // 3. 保存出库单
        return this.save(outboundDetail);
    }

    @Override
    public IPage<OutboundDetailVO> pageDetailList(OutboundDetailQueryDTO query) {
        // 1. 设置分页参数
        Page<Outbound> page = new Page<>(
                query.getPageNum() != null ? query.getPageNum() : 1,
                query.getPageSize() != null ? query.getPageSize() : 5
        );

        // 2. 构建查询条件
        LambdaQueryWrapper<Outbound> wrapper = new LambdaQueryWrapper<>();

        // 出库流水号模糊查询
        if (StringUtils.isNotBlank(query.getOutboundSerialNumber())) {
            wrapper.like(Outbound::getOutboundSerialNumber, query.getOutboundSerialNumber());
        }

        // 出库单号查询（通过outboundDetailId关联）
        if (StringUtils.isNotBlank(query.getOutboundNo())) {
            // 先查询匹配的出库明细ID
            LambdaQueryWrapper<OutboundDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.like(OutboundDetail::getOutboundNo, query.getOutboundNo());
            List<OutboundDetail> details = outboundDetailService.list(detailWrapper);
            if (!details.isEmpty()) {
                List<Integer> detailIds = details.stream()
                        .map(OutboundDetail::getId)
                        .map(Long::intValue)
                        .collect(Collectors.toList());
                wrapper.in(Outbound::getOutboundDetailId, detailIds);
            } else {
                // 如果没有匹配的出库单号，返回空结果
                return new Page<>(page.getCurrent(), page.getSize(), 0);
            }
        }

        // 产品名称查询（通过productId关联）
        if (StringUtils.isNotBlank(query.getProductName())) {
            // 先查询匹配的产品ID
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.like(Product::getProductName, query.getProductName());
            List<Product> products = productService.list(productWrapper);
            if (!products.isEmpty()) {
                List<Long> productIds = products.stream()
                        .map(Product::getProductId)
                        .collect(Collectors.toList());
                wrapper.in(Outbound::getProductId, productIds);
            } else {
                // 如果没有匹配的产品，返回空结果
                return new Page<>(page.getCurrent(), page.getSize(), 0);
            }
        }

        // 产品分类查询（通过productId关联）
        if (query.getCategory()!=null) {
            // 先查询匹配分类的产品ID
            LambdaQueryWrapper<Product> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.eq(Product::getCategory, query.getCategory());
            List<Product> categoryProducts = productService.list(categoryWrapper);
            if (!categoryProducts.isEmpty()) {
                List<Long> productIds = categoryProducts.stream()
                        .map(Product::getProductId)
                        .collect(Collectors.toList());
                wrapper.in(Outbound::getProductId, productIds);
            } else {
                // 如果没有匹配的分类，返回空结果
                return new Page<>(page.getCurrent(), page.getSize(), 0);
            }
        }

        // 按出库时间倒序排序
        wrapper.orderByDesc(Outbound::getOutboundTime);

        // 3. 执行分页查询
        IPage<Outbound> outboundPage = outboundService.page(page, wrapper);

        // 4. 转换为VO对象
        return outboundPage.convert(outbound -> {
            OutboundDetailVO vo = new OutboundDetailVO();

            // 设置出库基本信息
            vo.setOutboundSerialNumber(outbound.getOutboundSerialNumber());
            vo.setOutboundTime(outbound.getOutboundTime());
            vo.setOutboundType(outbound.getOutboundType());
            vo.setRemark(outbound.getRemark());

            // 设置出库单号（从OutboundDetail获取）
            OutboundDetail detail = outboundDetailService.getById(outbound.getOutboundDetailId());
            if (detail != null) {
                vo.setOutboundNo(detail.getOutboundNo());
                vo.setOutboundQuantity(detail.getOutboundQuantity());
            }

            // 设置产品信息
            if (outbound.getProductId() != null) {
                Product product = productService.getById(outbound.getProductId());
                if (product != null) {
                    vo.setProductName(product.getProductName());
                    vo.setProductSpec(product.getSpecification());
                    // 确保category是Integer类型
                    vo.setCategory(product.getCategory() != null ? product.getCategory().intValue() : null);
                }
            }

            // 设置单位信息
            if (outbound.getUnitId() != null) {
                Unit unit = unitService.getById(outbound.getUnitId());
                if (unit != null && unit.getUnitName() != null) {
                    vo.setUnit(unit.getUnitName());
                }
            }

            // 设置仓库信息
            if (outbound.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(outbound.getWarehouseId());
                if (warehouse != null && warehouse.getWarehouseName() != null) {
                    vo.setWarehouseName(warehouse.getWarehouseName());
                }
            }

            // 设置操作人信息
            if (outbound.getUId() != null) {
                TUser user = userService.getById(outbound.getUId());
                if (user != null && user.getUsername() != null) {
                    vo.setOperator(user.getUsername());
                }
            }

            return vo;
        });
    }


}




